from config import ini_op
import json, requests, pandas, duckdb, os
from time import strftime
from utils.path_utils import get_project_root
from database.duckdb.duckdb_base import get_connection


def run(llq, header, hszz):
  timenow = str(strftime("%Y%m%d%H%M%S"))
  nd, url_header, exportAccDept = ini_op.getinivalue('bmzd_config', 'kjnd', 'url_header', 'exportAccDept')
  url = url_header+exportAccDept
  data = '{"accOrgID":"'+hszz+'","year":"'+nd+'"}'
  result = requests.post(url, headers=header, json=json.loads(data), verify=False)
  rows = result.json()
  print(len(rows))

  conn = get_connection()
  df = pandas.DataFrame(rows)
  #df数据注册为临时表
  conn.register("temp_bmzd", df)
  #指定列创建新表
  conn.execute("""
      delete from t_api_bm where fiyear = """+nd+""";
      insert into t_api_bm (
        id,
        code,
        name_chs,
        fullname_chs,
        accorgid,
        orgcode,
        orgname,
        admindeptid,
        treeinfo_isdetail,
        treeinfo_layer,
        treeinfo_path,
        parentid,
        isdisable,
        disableyear,
        sortorder,
        fiyear,
        timestamp_createdon,
        timestamp_lastchangedon,
        esun_api_update)
      select ID,CODE,NAME$LANGUAGE$,FULLNAME$LANGUAGE$,ACCORGID,ACCORGID_CODE,ACCORGID_NAME,ADMINDEPTID,TREEINFO_ISDETAIL,TREEINFO_LAYER,
        TREEINFO_PATH,PARENTID,ISDISABLE,DISABLEYEAR,SORTORDER,'"""+nd+"""',TIMESTAMP_CREATEDON,TIMESTAMP_LASTCHANGEDON,'"""+timenow+"""'
      from temp_bmzd;
      """)
  conn.close()


  # os.makedirs(folderpath, exist_ok=True)
  # browser, context, page = llq
  # page.click('#toolbar_header_function')
  # page.fill('#search', '核算部门')
  # page.wait_for_timeout(2000)
  # try:
  #     page.wait_for_selector('ul.search--result-list', timeout=2000)
  # except Exception:
  #     page.click('.header--search')
  # page.locator('ul.search--result-list li').first.click()

  # page.click('#year .f-icon-lookup')
  # page.wait_for_selector('.lookup-tabs-content [title="'+nd+'"]')
  # page.wait_for_timeout(500)
  # page.locator('.lookup-tabs-content [title="'+nd+'"]').dblclick()

  # page.click('#accOrg .f-icon-lookup')
  # page.locator('.lookup-tabs-content [name="input-group-value"]').fill(hszz)
  # page.locator('.lookup-tabs-content [name="input-group-value"]').press('Enter')
  # page.wait_for_selector('[id^=rownode] .align-items-center span:text-matches(\"^'+hszz+'$\")')
  # page.wait_for_timeout(500)
  # page.locator('[id^=rownode] .align-items-center span:text-matches(\"^'+hszz+'$\")').last.dblclick()

  # page.locator('#button-confirm').last.click()


  # page.locator('#toolBarItem_export').last.click()
  # page.wait_for_selector('li.borderactive[title="核算部门导出"]')
  # id = page.query_selector('.borderactive a').get_attribute('id')
  # page.wait_for_selector("iframe#rtf_iframe_" + id[:-5])
  # frame = page.query_selector("iframe#rtf_iframe_" + id[:-5]).content_frame()

  # with page.expect_download(timeout=600000) as download_info:
  #   frame.click('[toolbarid="baritem_export"]')
  #   frame.click('.lee-dialog-table label[for="exportNewSet-1"]')
  #   frame.click('.lee-dialog-buttons .lee-btn-primary')
  #   download = download_info.value
  #   download.save_as(os.path.join(folderpath, nd+hszz+'部门字典导出'+download.suggested_filename[-5:]))

  
  # page.click('[title="核算部门导出"] div.nav-link-close')
  # page.click('[title="核算部门"] div.nav-link-close')


